package com.pwrd.tank;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * @Auther syc.
 * @Date 2016/10/18 15:46.
 */
public class TankDeadMsg implements Msg {

    int deadTankId;
    TankClient tc;
    int msgType = Msg.TANK_DEAD_MSG;

    public TankDeadMsg(TankClient tc) {
        this.tc = tc;
    }

    public TankDeadMsg(int id) {
        this.deadTankId = id;
    }

    @Override
    public void send(DatagramSocket ds, String IP, int udpPort) {
        ByteArrayOutputStream baos =
                new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        try {
            dos.writeInt(msgType);
            dos.writeInt(deadTankId);
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] buf = baos.toByteArray();
        DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(IP, udpPort));

        try {
            ds.send(dp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void parse(DataInputStream dis) {
        try {
            int id = dis.readInt();

            for (int i=0; i<tc.tanks.size(); i++) {
                Tank t = tc.tanks.get(i);
                if(t.id == id) {
                    t.setLive(false);
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
